import axios from '@/libs/api.request'

export function downloadFile (res, filename) {
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const downloadElement = document.createElement('a')
    let href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    if (!filename) {
        const { headers = null } = res
        if (headers && headers['content-disposition']) {
            const v = decodeURI(headers['content-disposition'].split('=')[1])
            filename = v || 'filename'
        }
    }
    downloadElement.download = filename || 'export'
    document.body.appendChild(downloadElement)
    downloadElement.click()
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
}

export const downloadTemplate = (data) => {
    return axios.request({
        url: '/fileManage/download/template',
        method: 'post',
        responseType: 'arraybuffer',
        data
    }).then(res => {
        if (res.status === 200) {
            downloadFile(res)
        }
        return res
    })
}
export const downloadDoc = (id, url) => {
    return axios.request({
        url: '/case/download',
        params: {
            caseId: id
        },
        responseType: 'arraybuffer',
        method: 'get'
    }).then(res => {
        if (res.status === 200) {
            downloadFile(res)
        }
        return res
    })
}
export const downloadQues = (id, url) => {
    return axios.request({
        url: '/testManage/export',
        data: {
            testIds: id
        },
        responseType: 'arraybuffer',
        method: 'post'
    }).then(res => {
        if (res.status === 200) {
            downloadFile(res)
        }
        return res
    })
}
export const download = (data, url) => {
    return axios.request({
        url: url,
        params: data,
        responseType: 'arraybuffer',
        method: 'get'
    }).then(res => {
        if (res.status === 200) {
            downloadFile(res)
        }
        return res
    })
}

export const importUrl = '/fileManage/import'
